import numpy as np
import pandas as pd
from recommend import Recommend
from fp_growth import fp_growth
from dsjxtjc_mysql import mmySQL
import random
import data_preparation.process_data
import csv



class Data():
    def __init__(self, mysql_obj, recommend_obj):
        self.mysql_obj = mysql_obj
        self.sale_rank = pd.read_csv("./data/sale_rank.csv", index_col=None, header=None)
        self.recommend_obj = recommend_obj

    def trans_format(self,input_data):  # 转换为满足recommend里所需的菜品名称的格式
        output_data = []
        for i in input_data:
            i = str(i)
            #print(i)
            if len(i) >= 5:
                if len(i)==6 and i[0]=='0':
                    i = i[1:]
                output_data.append(i)
        return output_data

    def get_user_order(self,user_id,customer_num):
                
        user_history = self.mysql_obj.select_data("select item_code, count(*) from qinghua_huiyuan_caipin where mem_mobile='%s' group by item_code" % user_id)
        #print("user_history: ",user_history)

        recommend_num = 50

        # 老用户 参照历史点单记录 
        # 点过的 + 剩下的随机
        if user_history: 
            user_order = []
            for his in user_history:
                user_order.append(his[0])
            #print("user_order", user_order)
            if(recommend_num>=len(user_order)):
                user_order = user_order[:recommend_num]
            else:    
                rand_num = recommend_num-len(user_order)
                food_ids = self.sale_rank.iloc[:,0]
                #print("food_ids",food_ids)
                rand_list = []
                while rand_num:
                    tmp = food_ids[np.random.randint(0,self.sale_rank.shape[0],1)[0]]
                    if tmp in user_order:
                        continue
                    else:
                        user_order.append(str(tmp))
                        rand_num-=1

        # 新用户 参照总销量
        # 销量前top80% + 剩下的随机
        else: 
            top_num = int(0.8 * recommend_num) #80%以销量前top个
            rand_num = int(0.2 * recommend_num) #20%随机点单
            top_list = self.sale_rank.iloc[:top_num, 0]
            rand_id_list = random.sample(range(top_num, self.sale_rank.shape[0]), rand_num)
            rand_list = self.sale_rank.iloc[rand_id_list, 0]
            user_order = pd.concat([top_list,rand_list])

        user_order = self.trans_format(user_order)
        #print("user_order", user_order)
        recommend_profit_list = recommend_obj.get_recommend_profit_list(user_order)
        food_package = recommend_obj.get_package(recommend_profit_list, customer_num)
        return food_package


class Matrics():
    def __init__(self, mysql_obj):
        self.mysql_obj = mysql_obj
        self.item_price = pd.read_csv(price_profit_list_dir,index_col=0)
        index = self.item_price.index
        index = [str(i) for i in list(index)]
        #print("index",index)
        self.item_price.index = index

    # 推荐覆盖率
    def coverage(self,prediction, user_order):
        intersection = list(set(prediction) & set(user_order))
        accuracy = len(intersection)/len(set(prediction))
        return accuracy

    # 利润差
    def profit_gap(self,prediction, user_order):
        user_price = 0
        for food in user_order:
            user_price += self.get_food_value(food)
        predic_price = 0
        for food in prediction:
            predic_price += self.get_food_value(food)
        profit = predic_price - user_price
        return profit

    def get_food_value(self,id):
        #return int(self.mysql_obj.select_data("select item_money from qinghua_huiyuan_caipin where item_code='%s'" % id)[0][0])
        if(len(id)==5 or (len(id)==6 and id[0]!='0')):
            return float(self.item_price.loc[id,"profit"])
        else:
            print("错误的菜名ID")
            return 0


if __name__ == "__main__":
    
    mysql_obj = mmySQL("localhost","root","admin","data")
    similarity_matrix_dir = "./data/similarity_matrix.csv"
    price_profit_list_dir = "./data/item_price.csv"
    people_average_num_food_dir = "./data/people_average_num_food.csv"
    people_average_num_type_dir = "./data/people_average_num_type.csv"
    sale_rank_dir = "./data/sale_rank.csv"
    food_rate_dir = "./data/food_rate.csv"

    customer_num = 10
    phone_number = "13783431022"

    recommend_obj  = Recommend(similarity_matrix_dir, price_profit_list_dir, people_average_num_food_dir,
                               people_average_num_type_dir, sale_rank_dir, food_rate_dir)

    order_obj = Data(mysql_obj, recommend_obj)
    customer_order = order_obj.get_user_order(phone_number, customer_num)

    prediction_order = recommend_obj.run(mysql_obj,phone_number,customer_num)
    #prediction_order = fp_growth.run(customer_num,phone_number) 

    matric = Matrics(mysql_obj)
    
    print("customer_order",customer_order)
    print("prediction_order", prediction_order)
    
    print("Rate of coverage: ", matric.coverage(prediction_order,customer_order))
    print("Profit gap: ", matric.profit_gap(prediction_order,customer_order))
    